package com.smart.village.big.screen.controller.bigscreen;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.smart.village.big.screen.domain.AjaxResult;
import com.smart.village.big.screen.service.AuthenticationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * 鉴权接口
 */
@Tag(name = "鉴权接口")
@RestController
@RequestMapping("/auth")
@Configuration
public class AuthenticationController {

    @Autowired
    private AuthenticationService authenticationService;
    Logger logger = Logger.getLogger(this.getClass().getName());

    @Operation(summary = "鉴权接口 单独获取token")
    @Parameters({
    })
    @RequestMapping("/getToken")
    public String getToken() {
        return authenticationService.getToken();
    }

    /**
     * 漠河数智乡村管理 - 全部数据权限
     *
     * @param username
     * @return
     */
    @Operation(summary = "漠河数智乡村管理 - 全部数据权限 ")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
    })
    @RequestMapping("/getAllList")
    public AjaxResult getAllList(@RequestParam String username) {
        try {
            JSONObject tokenId1 = authenticationService.getTownVillageList(username);
            if (!ObjectUtils.isEmpty(tokenId1)) {
                if (tokenId1.getBoolean("success")) {
                    String content = tokenId1.getString("content");
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    JSONArray menus = jsonObject.getJSONArray("menus");
                    StringBuilder unit01 = new StringBuilder();
                    StringBuilder org02 = new StringBuilder();
                    StringBuilder town03 = new StringBuilder();
                    StringBuilder village03 = new StringBuilder();
                    for (Object menu : menus) {
                        JSONObject menuObj = (JSONObject) menu;
                        if (menuObj.getString("path").equals("漠河市人民政府")) {
                            List<JSONObject> unit = flattenTree(menuObj,false);
                            for (JSONObject u : unit) {
                                if (!u.getString("parentName").equals("0")) {
                                    unit01.append("'").append(u.getString("name")).append("'").append(",");
                                }
                            }
                        }
                        if (menuObj.getString("path").equals("中共漠河市委员会")) {
                            List<JSONObject> org = flattenTree(menuObj,false);
                            for (JSONObject v : org) {
                                if (!v.getString("parentName").equals("0")) {
                                    org02.append("'").append(v.getString("name")).append("'").append(",");
                                }
                            }
                        }
                        if (menuObj.getString("path").equals("漠河市行政区划")) {
                            JSONArray subMenus = ((JSONObject) menu).getJSONArray("menus");
                            if (subMenus != null) {
                                // 遍历镇的菜单
                                for (Object subMenuObj : subMenus) {
                                    JSONObject subMenu = (JSONObject) subMenuObj;
                                    // 添加镇的 name 到列表
                                    town03.append("'").append(subMenu.getString("name")).append("'").append(",");
                                    JSONArray villageMenus = subMenu.getJSONArray("menus");
                                    if (villageMenus != null) {
                                        // 遍历村的菜单
                                        for (Object villageMenuObj : villageMenus) {
                                            JSONObject villageMenu = (JSONObject) villageMenuObj;
                                            // 添加村的 name 到列表
                                            village03.append("'").append(villageMenu.getString("name")).append("'").append(",");
                                        }
                                    }
                                }
                            }
                        }
                    }

                    JSONObject result = new JSONObject();
                    result.put("unit", !unit01.isEmpty() ? unit01.subSequence(0, unit01.length() - 1) : "");
                    result.put("party", !org02.isEmpty() ? org02.subSequence(0, org02.length() - 1) : "");
                    JSONObject area = new JSONObject();
                    area.put("town", !town03.isEmpty() ? town03.subSequence(0, town03.length() - 1) : "");
                    area.put("village", !village03.isEmpty() ? village03.subSequence(0, village03.length() - 1) : "");
                    result.put("area", area);
                    result.put("username", username);
                    return AjaxResult.success(result);
                }
            }
            return AjaxResult.error("获取失败", "failed");
        } catch (Exception e) {
            logger.fine(e.getMessage());
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 漠河数智乡村管理 -数据权限 - 漠河市行政区划  - 行政区划树形结构
     *
     * @param username
     * @return
     */
    @Operation(summary = "漠河数智乡村管理 -数据权限 - 漠河市行政区划  - 行政区划树形结构")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
    })
    @RequestMapping("/getTownVillageList")
    public AjaxResult getTownVillageList(@RequestParam String username) {
        try {
            JSONObject tokenId1 = authenticationService.getTownVillageList(username);
            if (!ObjectUtils.isEmpty(tokenId1)) {
                if (tokenId1.getBoolean("success")) {
                    String content = tokenId1.getString("content");
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    JSONArray menus = jsonObject.getJSONArray("menus");
                    JSONObject TownVillage = new JSONObject();
                    for (Object menu : menus) {
                        JSONObject menuObj = (JSONObject) menu;
                        if (menuObj.getString("path").equals("漠河市行政区划")) {
                            TownVillage = menuObj;
                        }
                    }
                    JSONArray newMenus = new JSONArray();
                    newMenus.add(TownVillage);
                    jsonObject.put("menus", newMenus);
                    return AjaxResult.success(jsonObject);
                }
            }
            return AjaxResult.error("获取失败", "failed");
        } catch (Exception e) {
            logger.fine(e.getMessage());
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 漠河数智乡村管理 -数据权限 - 中共漠河市委员会   - 党组织树形结构
     *
     * @param username
     * @return
     */
    @Operation(summary = "漠河数智乡村管理 -数据权限 - 中共漠河市委员会  - 党组织树形结构")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
    })
    @RequestMapping("/getPartyOrganizationTree")
    public AjaxResult getPartyOrganizationTree(@RequestParam String username) {
        try {
            JSONObject tokenId1 = authenticationService.getTownVillageList(username);
            if (!ObjectUtils.isEmpty(tokenId1)) {
                if (tokenId1.getBoolean("success")) {
                    String content = tokenId1.getString("content");
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    JSONArray menus = jsonObject.getJSONArray("menus");
                    JSONObject partTree = new JSONObject();
                    for (Object menu : menus) {
                        JSONObject menuObj = (JSONObject) menu;
                        if (menuObj.getString("path").equals("中共漠河市委员会")) {
                            partTree = menuObj;
                        }
                    }
                    return AjaxResult.success(partTree);
                }
            }
            return AjaxResult.error("获取失败", "failed");
        } catch (Exception e) {
            logger.fine(e.getMessage());
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 漠河数智乡村管理 -数据权限 - 中共漠河市委员会 - 党组织平行结构
     *
     * @param username
     * @return
     */
    @Operation(summary = "漠河数智乡村管理 -数据权限 - 中共漠河市委员会  - 党组织平行结构")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
    })
    @RequestMapping("/getPartyOrganizationList")
    public AjaxResult getPartyOrganizationList(@RequestParam String username) {
        try {
            JSONObject tokenId1 = authenticationService.getTownVillageList(username);
            if (!ObjectUtils.isEmpty(tokenId1)) {
                if (tokenId1.getBoolean("success")) {
                    String content = tokenId1.getString("content");
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    JSONArray menus = jsonObject.getJSONArray("menus");
                    if(CollectionUtils.isEmpty(menus)){

                        return AjaxResult.success(Lists.newArrayList());
                    }
                    JSONObject TownVillage = new JSONObject();
                    for (Object menu : menus) {
                        JSONObject menuObj = (JSONObject) menu;
                        if (menuObj.getString("path").equals("中共漠河市委员会")) {
                            TownVillage = menuObj;
                        }
                    }
                    JSONArray newMenus = new JSONArray();
                    newMenus.add(TownVillage);
                    jsonObject.put("menus", newMenus);
                    List<JSONObject> flatList = flattenTree(jsonObject,true);
                    flatList = new ArrayList<>(flatList);
                    return AjaxResult.success(flatList);
                }
            }
            return AjaxResult.error("获取失败", "failed");
        } catch (Exception e) {
            logger.fine(e.getMessage());
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 漠河数智乡村管理 -数据权限 - 漠河市人民政府  - 单位平行结构
     *
     * @param username
     * @return
     */
    @Operation(summary = "漠河数智乡村管理 -数据权限 - 漠河市人民政府  - 单位平行结构")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
    })
    @RequestMapping("/getUnitList")
    public AjaxResult getUnitList(@RequestParam String username) {
        try {
            JSONObject tokenId1 = authenticationService.getTownVillageList(username);
            if (!ObjectUtils.isEmpty(tokenId1)) {
                if (tokenId1.getBoolean("success")) {
                    String content = tokenId1.getString("content");
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    JSONArray menus = jsonObject.getJSONArray("menus");
                    JSONObject TownVillage = new JSONObject();
                    for (Object menu : menus) {
                        JSONObject menuObj = (JSONObject) menu;
                        if (menuObj.getString("path").equals("漠河市人民政府")) {
                            TownVillage = menuObj;
                        }
                    }
                    JSONArray newMenus = new JSONArray();
                    newMenus.add(TownVillage);
                    jsonObject.put("menus", newMenus);

                    List<JSONObject> flatList = flattenTree(jsonObject, false);
                    flatList = new ArrayList<>(flatList);
                    return AjaxResult.success(flatList);

                }
            }
            return AjaxResult.error("获取失败", "failed");
        } catch (Exception e) {
            logger.fine(e.getMessage());
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 漠河数智乡村管理 -数据权限 - 漠河市行政区划 - 根据父级code获取子级列表 单层
     *
     * @param username
     * @return
     */
    @Operation(summary = "漠河数智乡村管理 -数据权限 - 漠河市行政区划 - 根据父级code获取子级列表 单层")
    @Parameters({
            @Parameter(name = "partyOrganizationSerialNumber", description = "用户名"),
            @Parameter(name = "parentName", description = "父级编码"),
    })
    @RequestMapping("/getChildVillageList")
    public AjaxResult getChildVillageList(@RequestParam String username, @RequestParam(required = false, defaultValue = "232723") String parentName) {
        try {
            JSONObject tokenId1 = authenticationService.getTownVillageList(username);
            if (!ObjectUtils.isEmpty(tokenId1)) {
                if (tokenId1.getBoolean("success")) {
                    String content = tokenId1.getString("content");
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    List<JSONObject> flatList = flattenTree(jsonObject, false);
                    flatList = flatList.stream().filter(f -> f.getString("parentName").equals(parentName)).collect(Collectors.toCollection(ArrayList::new));
                    return AjaxResult.success(flatList);
                }

            }
            return AjaxResult.error("获取失败", "failed");
        } catch (Exception e) {
            logger.fine(e.getMessage());
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 漠河数智乡村管理 -数据权限 - 党建小程序我的 图标
     *
     * @param username
     * @return
     */
    @Operation(summary = "漠河数智乡村管理 -数据权限 - 党建小程序我的 图标")
    @Parameters({
            @Parameter(name = "username", description = "用户名"),
    })
    @RequestMapping("/getPartyOrganizationMicroMyIcon")
    public AjaxResult getPartyOrganizationMicroMyIcon(@RequestParam String username) {
        try {
            JSONObject tokenId1 = authenticationService.getPartyOrganizationMicroMyIcon(username);

            if (!ObjectUtils.isEmpty(tokenId1)) {
                if (tokenId1.getBoolean("success")) {
                    JSONObject result = new JSONObject();
                    List<JSONObject> memberList = Lists.newArrayList();
                    List<JSONObject> memberList2 = Lists.newArrayList();
                    List<JSONObject> buildList = Lists.newArrayList();
                    String content = tokenId1.getString("content");
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    JSONArray menus = jsonObject.getJSONArray("menus");
                    for (Object menu : menus) {
                        JSONObject menuJson = new JSONObject((Map<String, Object>) menu);
                        if (menuJson.getString("text").equals("党员事务")) {
                            dealMenuChild(memberList, menuJson);
                            result.put("memberList", memberList);
                        }
                        if (menuJson.getString("text").equals("党建事务管理")) {
                            JSONArray menusChild = menuJson.getJSONArray("menus");
                            for (Object child : menusChild) {
                                JSONObject childJson = new JSONObject((Map<String, Object>) child);
                                if (childJson.getString("text").equals("党组织事务")) {
                                    dealMenuChild(memberList2, childJson);

                                }
                                result.put("memberList2", memberList2);

                                if (childJson.getString("text").equals("党建事务")) {
                                    dealMenuChild(buildList, childJson);
                                }
                                result.put("buildList", buildList);
                            }
                        }
                    }
                    return AjaxResult.success(result);
                }

            }
            return AjaxResult.error("获取失败", "failed");
        } catch (Exception e) {
            logger.fine(e.getMessage());
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 漠河数智乡村管理 -村民端切换按钮列表权限
     *
     * @param iDCardNumber
     * @return
     */
    @Operation(summary = "漠河数智乡村管理 -村民端切换按钮列表权限")
    @Parameters({
            @Parameter(name = "iDCardNumber", description = "身份证号"),
    })
    @RequestMapping("/getResidentChangeButtonPermissionList")
    public AjaxResult getResidentChangeButtonPermissionList(@RequestParam String iDCardNumber) {
        try {
            List<JSONObject> tokenId1 = authenticationService.getResidentChangeButtonPermissionList(iDCardNumber);
            return AjaxResult.success(tokenId1);

        } catch (Exception e) {
            logger.fine(e.getMessage());
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    private void dealMenuChild(List<JSONObject> memberList, JSONObject menuJson) {
        JSONArray menusChild = menuJson.getJSONArray("menus");
        for (Object child : menusChild) {
            JSONObject childJson = new JSONObject((Map<String, Object>) child);
            String id = childJson.getString("name");
            String name = childJson.getString("text");
            String img = childJson.getString("icon");
            JSONObject authJson = new JSONObject();
            authJson.put("id", id);
            authJson.put("name", name);
            authJson.put("img", img);
            memberList.add(authJson);
        }
    }


    // 递归方法，将树形结构转换为平级列表
    public static List<JSONObject> flattenTree(JSONObject root, boolean isParty) {
        List<JSONObject> flatList = new ArrayList<>();
        flattenHelper(root, "0", flatList,isParty);
        return flatList;
    }

    // 递归辅助方法
    private static void flattenHelper(JSONObject node, String parentName, List<JSONObject> flatList, boolean isParty) {
        node.put("parentName", parentName);
        if (node == null) {
            return;
        }
        // 将当前节点值添加到平级列表
        if (!node.containsKey("menus")) {
            node.remove("menus");
        }
        if (!"menubar".equals(node.getString("type"))) {
            if(isParty){
                if(node.getJSONArray("menus").isEmpty()) {
                    flatList.add(node);
                }
            }else{
                flatList.add(node);
            }

        }
        // 递归遍历子节点
        if (!CollectionUtils.isEmpty(node.getJSONArray("menus"))) {
            for (Object child : node.getJSONArray("menus")) {
                flattenHelper((JSONObject) child, node.getString("name"), flatList, isParty);
                node.remove("menus");
            }
        } else {
            node.remove("menus");
        }

    }

}
